<?php
namespace control;
/*
* 劳动报酬清单类
*/

class laborSalaryClass extends adIndexClass
{
    private const page = 'laborSalary';
    private const table = 'labor_salary';
    private const table_detail = 'labor_salary_detail';
    private const table_company = 'labor_company';
    private const title = '劳动报酬清单';
    public array $stateOption = ['草稿', '审核中', '已通过'];

    /*列表-查询条件*/
    public function home()
    {
        //生成查询表单
        $html =
            text(array("name" => "orderNo", "title" => "单据编号")) .
            text(array("name" => "month", 'laydate' => ['type' => 'month'], "title" => "月份")) .
            text(array("name" => "agreementNo", "title" => "派遣协议编号")) .
            selectMultiple(["name" => "companyId", 'title' => '派遣单位', 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'labor_company', 'where' => "state = '启用' order by orderNo", 'class' => 'text']) .
            text(array("name" => "startTime", 'class' => 'width200', 'laydate' => ['type' => 'date', 'range' => '~'], "title" => "单据日期-单据日期")) .
            select(array("name" => "state", "title" => "审批状态", "option" => $this->stateOption));
        //返回
        return $this->homeFun($this->search($html));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),
        );
        //全等查询数组
        $equal = array(
            'companyId' => $this->post('companyId'),
            "state" => $this->post('state'),//状态
        );
        $and = "";
        if ($this->post('startTime')) {
            $and .= self::timeComparison($this->post('startTime'));
        }
        if ($this->post('agreementNo')) {
            $and .= " and aid in (select id from labor_agreement where orderNo like '%" . $this->post('agreementNo') . "%')";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;

        $page = $this->page(array("table" => self::table, "where" => $where, "order" => "month desc"));
        //获取表头
        $checkAll = $this->checkAll("listForm", "listId");
        $tr[] = array($checkAll, "单据编号", "月份", "派遣单位", '派遣协议编号', '清单人数', '申请人', '劳务报酬金额合计（' . static::$unit . '）', '单据日期', '状态');
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box" => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            $company = query(self::table_company, "id = '$array[companyId]'");
            $laborAgreement = query('labor_agreement', "id = '$array[aid]'");
            $totalPeople = static::total(array('table' => self::table_detail, "where" => "orderId = '$array[id]'"));
            $money = find(array('table' => self::table_detail, 'where' => "orderId = '$array[id]'", 'sum' => "money"));
            $tr[] = array(
                $this->dominate($dominate), $array['orderNo'], $array['month'], $company['name'], $laborAgreement['orderNo'], $totalPeople, self::findStaff($array['stid']),
                $money, $array['time'], $array['state']);
        }
        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .= "<span onclick=\"layer('" . self::page . "','edit',{})\" class='spanButton'>新增</span>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'del'})\">删除</span>\n";
        }
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . space . $this->tableMany(array("tr" => $tr)) . "</form>" . $page['button'] . $this->js() . clear;
        return json_encode($json, 320);
    }


    public function js()
    {
        return <<<eof
<script>
function getOrderInfo(e){
    $.post(root+'control/adIndex.html?cla=laborSalary&fun=getOrderInfo',{id:e.value},function(res) {
        $("#orderNo").empty().append(res.html)
    },'json')
}
</script>
eof;

    }

    public function getOrderInfo()
    {
        $json['html'] = selectMultiple(["name" => "aid", 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'orderNo', 'table' => 'labor_agreement', 'where' => "state = '已通过' and companyId = '" . $this->post('id') . "' order by orderNo", 'class' => 'text']);
        return json_encode($json, 320);
    }

    /**
     * 编辑页
     *
     * @return string
     */
    public function edit(): string
    {
        //生成表单
        $html = $this->layerEdit(array("table" => array(
            array(
                must . "月份：" => text(array('name' => 'month', 'laydate' => ['type' => 'month'], 'value' => date('Y-m'))),
            ),
            array(
                must . "派遣单位" => selectMultiple(["name" => "companyId", 'change' => 'getOrderInfo', 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'name', 'table' => 'labor_company', 'where' => "state = '启用' order by orderNo", 'class' => 'text'])
            ),
            array(
                must . "协议编号" => "<span id='orderNo'>" . selectMultiple(["name" => "aid", 'title' => '请选择', 'sqlId' => 'id', 'sqlField' => 'orderNo', 'table' => 'labor_agreement', 'where' => "state = '已通过' and companyId = '' order by orderNo", 'class' => 'text']) . "</span>"
            )
        )));
        //返回
        return $this->layer(array("title" => "新增", "height" => 320, "width" => 800, "html" => $html));
    }

    public function editEdit()
    {
        $id = $this->post('id') ?: self::getId();
        $field = [
            'month' => $this->post('month'),
            'companyId' => $this->post('companyId'),
            'aid' => $this->post('aid'),
        ];
        $annotation = [
            'month' => '月份',
            'companyId' => '派遣单位',
            'aid' => '协议编号',
        ];
        $rules = [
            'month' => 'required',
            'companyId' => 'required',
            'aid' => 'required',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $json['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        //判断
        if (!$this->power(self::page, "edit")) {
            $json['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::total(array('table' => self::table, "where" => "month = '$field[month]' and companyId = '$field[companyId]' and aid = '$field[aid]' and id !='$id'")) > 0) {
            $json['warn'] = '已存在此月份的报酬清单';
        } else {
            $where = " id = '$id' ";
            $info = query(self::table, $where);
            if (!$info['id']) {
                $userNo = codeTemplateClass::generateCode(self::page,[
                    'prefix' => 'LWBC' . date('Ymd'),
                    'table' => self::table,
                    'field' => 'orderNo',
                    'where' => '',
                ],$field);
                $department = query('department', "id = '" . $this->controlJob['departmentId'] . "'");
                $field = array_merge($field, [
                    'id' => $id,
                    'orderNo' => $userNo,
                    'stid' => $this->control['stid'],
                    'deptName' => $department['name'],
                    'state' => '草稿',
                ]);
                $json['warn'] = static::insert(["table" => self::table, "field" => $field]);
            } else {
                $json['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
            }
            if (in_array($json['warn'], ["新增成功", "更新成功"])) {
                //添加日志
                $type = mb_substr($json['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                //返回
                $_SESSION['warn'] = $json['warn'];
                $json['warn'] = 2;
                $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . $id;
            }
        }
        resp:
        return json_encode($json, 320);
    }

    /**
     * 审核按钮
     *
     * @param $info
     * @return array
     */
    public function auditButton($info): array
    {
        $button = [];
        if ($info['state'] == '草稿' || auditClass::auditFlag(self::table, $info['id'], 'selfChoose')) {
            $button[] = [
                "name" => '提交审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                'style' => 'li-btn-blue-bg',
                "post" => [
                    "act" => 'start', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'name' => '劳动报酬清单',
                        'table' => self::table,
                        'process' => [
                            // 预览函数
                            'detail' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'detail',
                            ],
                            //执行发起时验证函数
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        // 审批并判断是否有权限
        if ($info['state'] == '审核中' && auditClass::auditFlag(self::table, $info['id'])) {
            $button[] = [
                "name" => '审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                // 以下参数固定格式
                "post" => [
                    "act" => 'approval', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿', '已通过'],
                        ],
                        // 审核时回调
                        'process' => [
                            //执行首次审核时验证
                            'before' => [
                                'cla' => $this->get('cla'),
                                'fun' => '',
                            ],
                            //执行末次审核后处理
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'finish',
                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
                'style' => 'li-btn-blue-bg',
            ];
            $button[] = [
                "name" => '添加审批人',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'addApprover', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];
            $button[] = [
                "name" => '转交',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'transfer', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                    ], 320)),
                ],
            ];

        }

        // 撤销审批
        if (auditClass::auditFlag(self::table, $info['id'], 'cancel') && $info['state'] != '草稿') {
            $button[] = [
                "name" => '撤销审批',
                "type" => "弹出层",
                "cla" => 'audit',
                "fun" => "operate",
                "post" => [
                    "act" => 'cancel', "id" => $info['id'], 'body' => self::encryptDecrypt(json_encode([
                        'table' => self::table,
                        // 当前状态
                        'state' => $info['state'],
                        // 变更
                        'field' => ['state'],   //变更字段 可多个
                        'value' => [
                            'state' => ['草稿'],
                        ],
                        'process' => [
                            //完成发起后执行函数
                            'after' => [
                                'cla' => $this->get('cla'),
                                'fun' => 'cancelFun',
                                'data'=>['id'=>$info['id']]
                            ],
                        ],
                    ], 320)),
                ],
            ];
        }
        return $button;
    }

    public function cancelFun($data){
        delete(array('table'=>'record','where'=>"sourceId = '$data[id]'"));
    }
    public function finish($data){
        $info = query(self::table, " id = '{$data['id']}'");
        $money = find(array('table'=>self::table_detail,'where'=>"orderId = '$info[id]'",'sum'=>"money"));
        $balance = find(array('table' => "record", 'where' => "typeId = '$info[companyId]'", 'sum' => "money"));
         insert(array(
           'table'=>'record',
           'field'=>[
               'type'=>'派遣单位',
               'typeId'=>$info['companyId'],
               'targetDate'=>date('Y-m-d',strtotime($info['time'])),
               'classify'=>'劳动报酬清单',
               'direction'=>'+',
               'money'=>$money,
               'balance'=>$balance+$money,
               'orderNo'=>$info['orderNo'],
               'sourceTable'=>self::table,
               'sourceId'=>$info['id'],
               'text'=>'劳动报酬清单【'.$info['orderNo'].'】',
               'stName'=>self::findStaff($info['stid']),
           ]
        ));
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query(self::table, " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此' . self::title;
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
                "menu" => [
                    'detail' => '基本信息',
                    'peopleList' => '报酬清单',
                ],
            );

            $button = [];
            if ($this->power(self::page, "edit") && $info['state'] == '草稿') {
                $button[] = [
                    "name" => "上传附件",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "uploadFile",
                    "post" => ["id" => $info['id']],
                ];
            }
            if ($this->power(self::page, "del") && $info['state'] == '草稿') {
                //按钮
                $button[] = [
                    "name" => "删除",
                    "type" => "弹出层",
                    "cla" => $this->get('cla'),
                    "fun" => "operate",
                    "post" => ["act" => 'del', "id" => $info['id']],
                ];
            }
            //审核按钮
            $button = array_merge($button, $this->auditButton($info));
            $company = query(self::table_company, "id = '$info[companyId]'");
            $orderInfo = query('labor_agreement', "id = '$info[aid]'");
            $audit = query('audit', " targetId = '$info[id]'");
            //生成表单
            $data['html'] = $this->tableShow(array(
                "button" => $button,
                array(
                    array(
                        "单据编号" => $info['orderNo'],
                        "月份" => $info['month'],

                    ),
                    array(
                        "派遣单位" => $company['name'],
                        "派遣协议编号" => $orderInfo['orderNo'],
                    ),
                    array(
                        "申请人部门" => $info['deptName'],
                        "申请人" => self::findStaff($info['stid']),
                        "创建时间" => $info['time'],
                    ),
                    array(
                        "提交时间" => self::null($audit['commitTime']),
                        "状态" => $info['state'],
                    ),
                ),
                '附件' => array(
                    array(
                        fileUploadClass::showFile($info['id'], '劳动报酬清单')
                    )
                ),
                '流程' => array(
                    array(
                        auditClass::auditRecord(self::table, $info['id']),
                    ),
                ),
            ));
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }


    public function uploadFile(): bool|string
    {
        //生成表单
        $html = $this->layerEdit(array(
            "table" => array(
                array(
                    fileUploadClass::addFileComponent($this->post('id'), '劳动报酬清单', self::page, 'laborSalaryUploadFileForm')
                ),
            )
        ));
        //返回
        return $this->layer(array("title" => "上传附件", "height" => 300, "width" => 900, "html" => $html));
    }

    public function uploadFileEdit(): bool|string
    {
        $fileIdArr = $this->post('fileId') ?: [];
        $id = $this->post('id');
        if (!$this->power(self::page, 'edit')) {
            $json['warn'] = '你还没有编辑权限';
        } elseif (empty($id)) {
            $json['warn'] = '未找到ID';
        } else {
            $warn = update(array('table' => 'file', 'field' => ['targetId' => $id], 'where' => " targetId = '' and id in ('" . implode("','", $fileIdArr) . "')"));
            if (in_array($warn, ['新增成功', '更新成功'])) {
                $json['warn'] = 2;
                $_SESSION['warn'] = '上传成功';
            } else {
                $json['warn'] = '上传失败';
            }
        }
        return json_encode($json, 320);
    }


    /**
     * 派遣清单
     */
    public function peopleList(): bool|string
    {
        $html =
            text(array("name" => "name", "title" => "姓名")) .
            text(array("name" => "tel", "title" => "联系方式")) .
            text(array("name" => "idCard", "title" => "身份证号")) .
            hidden(array('name' => 'id', 'value' => $this->get('id')));
        $json['html'] = $this->search($html);
        return json_encode($json, 320);
    }

    /**
     * 派遣清单
     * @return bool|string
     */
    public function peopleListSearch(): bool|string
    {
        $info = query(self::table, "id = '" . $this->post('id') . "'");
        //全等查询数组
        $equal = array(
        );
        $like = array(
            "name" => $this->post('staffName'),//员工
        );
        $and = " and orderId = '$info[id]'";
        if (!empty($this->post('departmentId'))) {
            //部门
            $and .= " and jobId in (select id from job where departmentId = '{$this->post('departmentId')}') ";
        }
        //获取查询结果
        $where = search(array("=" => $equal, "like" => $like)) . $and;
        $page = $this->page(array("table" => self::table_detail, "where" => $where, "order" => " list asc"));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        $_SESSION[self::page]['id'] = $info['id'];
        $tr = '';
        //获取记录
        foreach ($page['array'] as $array) {
            $tr .= <<<eof
                 <tr>
                     <td><label class="listCheckbox"><input name="listId[]" type="checkbox" value="$array[id]"><span></span></label></td>
                     <td>{$array['name']}</td>
                     <td>{$info['month']}</td>
                     <td>{$array['workDay']}</td>
                     <td>{$array['salaryDay']}</td>
                     <td>{$array['baseMoney']}</td>
                     <td>{$array['jobMoney']}</td>
                     <td>{$array['telFee']}</td>
                     <td>{$array['trafficFee']}</td>
                     <td>{$array['performance']}</td>
                     <td>{$array['workAgeFee']}</td>
                     <td>{$array['educationFee']}</td>
                     <td>{$array['jobTitleFee']}</td>
                     <td>{$array['temperatureFee']}</td>
                     <td>{$array['overtimeFee']}</td>
                     <td>{$array['otherFee']}</td>
                     <td>{$array['leaveMoney']}</td>
                     <td>{$array['lateMoney']}</td>
                     <td>{$array['otherDecMoney']}</td>
                     <td>{$array['money']}</td>
                     <td>{$array['text']}</td>
                     <td>{$array['idCard']}</td>
                     <td>{$array['tel']}</td>
                 </tr>
eof;
        }

        $html = <<<eof
<div class="table_many_shell">
<table id="subjectTable" class="tableMany">
    <thead>
        <tr>
            <td rowspan="2" style="vertical-align:middle"><label title="全选" class="listCheckbox"><input type="checkbox" form="listForm" name="listId" onchange="checkAll(this)"><span></span></label></td>
            <td rowspan="2" style="vertical-align:middle">姓名</td>
            <td rowspan="2" style="vertical-align:middle">月份</td>
            <td rowspan="2" style="vertical-align:middle">出勤天数</td>
            <td rowspan="2" style="vertical-align:middle">受薪天数</td>
            <td colspan="15" class="center">工结构明细</td>
            <td rowspan="2" style="vertical-align:middle" class="center">备注</td>
            <td rowspan="2" style="vertical-align:middle" class="center">身份证号</td>
            <td rowspan="2" style="vertical-align:middle" class="center">手机号</td>
        </tr>
        <tr>
            <td>基本工资</td><td>岗位工资</td>
            <td>通讯补贴</td><td>交通补贴</td>
            <td>绩效工资</td><td>工龄工资</td>
            <td>学历津贴</td><td>职称津贴</td>
            <td>高温补贴</td><td>加班补贴</td>
            <td>其他补贴</td><td>病事假扣款</td>
            <td>迟到早退</td><td>其他扣款</td>
            <td>应发工资</td>
        </tr>
    </thead>
    <tbody>
     {$tr}
    </tbody>
</table>
</div>
<style>
#subjectTable{margin-left: 0;}
</style>
eof;

        //控件
        $button = "";
        if ($this->power(self::page, "edit")) {
            $button .=  importTemplateClass::importTemplateButton(self::page).
                $this->upButton(array("title" => "导入", "fun" => "importData"));
        }
        if ($this->power(self::page, "edit")) {
            $button .= "  <a href='" . root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportData'><span class='spanButton'>导出</span></a>\n";
        }
        if ($this->power(self::page, "del")) {
            $button .= "<span class='spanButton' onclick=\"layer('{$this->get('cla')}', 'operate', {'act': 'delMx'})\">删除</span>\n";
        }
        $money = find(array('table' => self::table_detail, 'where' => "orderId = '$info[id]'", 'sum' => 'money'));
        $button .= "<span style='margin-left: 20px;font-weight: bold;'>应发合计：{$money}</span>";
        //返回
        $json['html'] = $page['hint'] . $button . "<form class='listForm' name='recordForm'>" . space . $html . "</form>" . $page['button'];
        return json_encode($json, 320);
    }

    /**
     * 下载模板
     */
    public function downloadModel()
    {
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $title = ['*姓名', '*身份证号', '*手机号码', '出勤天数', '受薪天数', '基本工资', '岗位工资', '通讯补贴', '交通补贴', '绩效工资', '工龄工资', '学历津贴', '职称津贴', '高温补贴',
                '加班补贴', '其他补贴', '病事假扣款', '迟到早退', '其他扣款', '应发工资', '备注'];
            $data[] = ['张三', '500223199412011XXX', '13000000000', '22', '22', 3000, 2000, 100, 100, 0, 100, 0, 0, 0, 20,
                0, 0, 0, 0, 5320, ''];
            $text = $this->control['name'] . "下载了劳动报酬清单导入模板";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, '劳动报酬清单导入模板.xlsx');
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /*数据导入分析*/
    public function importData()
    {
        $id = $_SESSION[self::page]['id'];
        $info = query(self::table, "id = '$id'");
        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } elseif (empty($id)) {
            $_SESSION['warn'] = '未找到报酬清单ID';
        } elseif ($info['state'] != '草稿') {
            $_SESSION['warn'] = '劳动报酬清单不是草稿状态，不能编辑';
        } else {
            $data = $this->importHead(format: [
                1 => \Vtiful\Kernel\Excel::TYPE_STRING,
                2 => \Vtiful\Kernel\Excel::TYPE_STRING,
            ]);
            $x = 0;
            $text = '';
            foreach ($data as $i => $row) {
                if ($i > 0) {
                    $cell = formSubArray($row);
                    $detail = query(self::table_detail, " idCard = '$cell[1]' and orderId = '$id'");
                    $labor = query('labor', "idCard = '$cell[1]'");
                    if (!empty($detail['id'])) {
                        $text .= "第【{$i}】行：已存在此人员<br>";
                    } elseif (empty($labor['id'])) {
                        $text .= "第【{$i}】行：未在劳务名册中找到此人员<br>";
                    } else {
                        $field = [
                            "id" => self::getId(),
                            'orderId' => $id,
                            'laborId' => $labor['id'],
                            'name' => $cell[0],
                            'idCard' => $cell[1],
                            'tel' => $cell[2],
                            'salaryDay' => $cell[4],
                            'workDay' => $cell[3],
                            'baseMoney' => $cell[5],
                            'jobMoney' => $cell[6],
                            'telFee' => $cell[7],
                            'trafficFee' => $cell[8],
                            'performance'=>$cell[9],
                            'workAgeFee' => $cell[10],
                            'educationFee' => $cell[11],
                            'jobTitleFee' => $cell[12],
                            'temperatureFee' => $cell[13],
                            'overtimeFee' => $cell[14],
                            'otherFee' => $cell[15],
                            'leaveMoney' => $cell[16],
                            'lateMoney' => $cell[17],
                            'otherDecMoney' => $cell[18],
                            'money' => $cell[19],
                            'text' => $cell[20],
                        ];
                        $annotation = [
                            'name' => '姓名',
                            'tel' => '手机号',
                            'idCard' => '身份证号',
                        ];
                        $rules = [
                            'name' => 'required',
                            'tel' => 'required|tel',
                            'idCard' => 'required|id_card',
                        ];
                        // 校验是否符合规则
                        $vt = new \verify();
                        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
                        if ($result === false) {
                            $text .= "第【{$i}】行：" . $vt->getErrs()[0] . "<br>";  // 多个规则提示最前面一条
                            continue;
                        } else {
                            $warn = insert(["table" => self::table_detail, "field" => $field]);
                            if (in_array($warn, ["新增成功", "更新成功"])) {
                                $x++;
                                $text .= "第【{$i}】行：导入成功<br>";
                            } else {
                                $text .= "第【{$i}】行：导入失败：编辑失败<br>" . $warn;
                            }
                        }
                    }
                }
            }
            $text = $this->control['name'] . '导入了文件：' . $_FILES['file']['name'] . '：' . $text;
            $this->logText(["type" => self::page, "text" => $text]);
            $warn = "成功导入" . $x . "条数据，详情请查看日志！";
            $_SESSION['warn'] = $warn;
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    /**
     * 导出
     */
    public function exportData()
    {
        $id = $_SESSION[self::page]['id'];

        if (!$this->power(self::page, 'edit')) {
            $_SESSION['warn'] = '你还没有劳务派遣协议的编辑权限';
        } elseif (empty($id)) {
            $_SESSION['warn'] = '未找到派遣协议ID';
        } else {
            $info = query(self::table, "id = '$id'");
            $data = [];
            $sql = $_SESSION[self::page]['sql'];
            $title = ['姓名', '月份', '身份证号', '手机号码', '出勤天数', '受薪天数', '基本工资', '岗位工资', '通讯补贴', '交通补贴', '绩效工资', '工龄工资', '学历津贴', '职称津贴', '高温补贴',
                '加班补贴', '其他补贴', '病事假扣款', '迟到早退', '其他扣款', '应发工资', '备注'];
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $data[] = [$array['name'], $info['month'], $array['idCard'], $array['tel'], $array['workDay'], $array['salaryDay'], $array['baseMoney'], $array['jobMoney'], $array['telFee'], $array['trafficFee'], $array['performance'], $array['workAgeFee'], $array['educationFee'], $array['jobTitleFee'],
                        $array['temperatureFee'], $array['overtimeFee'], $array['otherFee'], $array['leaveMoney'], $array['lateMoney'], $array['otherDecMoney'], $array['money'], $array['text']];
                }
            }
            $text = $this->control['name'] . "导出了{$info['month']}劳动报酬清单";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "{$info['month']}劳动报酬清单.xlsx");
        }
        header("Location:" . getenv("HTTP_REFERER"));
        exit(0);
    }


    // 操作中转
    public function operate()
    {
        $act = $this->post('act') ?? '';
        $pwd = false; // 需要密码
        $form = $power = '';
        switch ($act) {
            case 'delMx':
                $act = 'del';
                $msg = '删除报酬清单' . self::title;
                $title = self::page . 'DetailDelete';
                $function = 'deleteMx';
                $form = self::page . 'OperateForm, recordForm';
                $power = '';
                break;
            default:
                $act = 'del';
                $msg = '删除' . self::title;
                $title = self::page . 'Delete';
                $function = 'delete';
                $form = self::page . 'OperateForm, listForm';
                $power = '';
                break;
        }
        if (!$this->power(self::page, $act)) {
            $_SESSION['warn'] = '你还没有' . $msg . '的权限';
            $json = [
                'warn' => 2,
                'href' => root . 'control/adIndex.html?cla=' . $this->get('cla') . '&fun=home',
            ];
        } else {
            return $this->confirm([
                'title' => $title,
                'function' => $function,
                'form' => $form,
                'power' => $power,
                'pwd' => $pwd,
            ]);
        }

        resp:
        return json_encode($json, 320);
    }

    /**
     * 删除
     *
     * @return bool|string
     */
    public function delete()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table, " id = '$id' ");
                if ($info['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table, "where" => " id = '$id' "));
                    delete(array("table" => self::table_detail, "where" => " orderId = '$id' "));
                    //删除audit表记录
                    delete(array('table' => 'audit', 'where' => "targetId = '$id'"));
                    //删除待办事项
                    delete(array("table" => "backlog", "where" => " typeId = '$id' "));
                    //删除审批记录
                    delete(array("table" => "auditing_follow", "where" => " typeId = '$id' "));
                    //删除消息提醒
                    delete(array("table" => "message", "where" => " typeId = '$id' "));
                    $all = find(array('table' => 'file', 'where' => "targetId = '$id'"));
                    foreach ($all['array'] as $val) {
                        fileDelete($val['src']);
                        delete(array("table" => 'file', "where" => " id = '$val[id]' "));
                    }
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了" . self::title . "，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=home";
        }
        return json_encode($json, 320);
    }

    public function deleteMx()
    {
        $array = $this->post('listId') ?? $this->post('id');
        if (!$this->power(self::page, "del")) {
            $json['warn'] = "你没有删除的权限";
        } elseif (empty($array)) {
            $json['warn'] = "你一个数据都没有选择呢";
        } else {
            $text = "";
            $x = 0;
            $array = is_array($array) ? $array : [$array];
            foreach ($array as $id) {
                $info = query(self::table . '_detail', " id = '$id' ");
                $parent = query(self::table, " id = '$info[orderId]' ");
                if ($parent['state'] != '草稿') {
                    $warn = "不是草稿状态，暂不能删除";
                } else {
                    //最后删除基本参数
                    delete(array("table" => self::table . '_detail', "where" => " id = '$id' "));
                    //返回
                    $warn = "删除成功";
                    $x++;
                }
                $text .= self::title . "ID【" . $info['id'] . "】" . $warn . "。<br>";
            }
            //添加日志
            $text = $this->control['name'] . "删除了派遣清单，结果如下：<br>" . $text;
            $this->logText(array("type" => self::page, "text" => $text));
            $_SESSION['warn'] = "删除了" . $x . "个" . self::title . "，详情见系统日志。";
            $json['warn'] = 2;
            $json['href'] = root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=detail&id=" . ($parent['id'] ?? '');
        }
        return json_encode($json, 320);
    }
}

